﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Eagles.Application.Model;
using Eagles.Application.Model.Branch.Requset;
using Eagles.Application.Model.Enums;
using Eagles.Application.Model.PartyMember.Model;
using Eagles.Application.Model.PartyMember.Requset;
using Eagles.Application.Model.PartyMember.Response;
using Eagles.Base;
using Eagles.Base.Cache;
using Eagles.Base.Configuration;
using Eagles.Base.Md5Helper;
using Eagles.DomainService.Model.Oper;
using Eagles.DomainService.Model.Org;
using Eagles.DomainService.Model.User;
using Eagles.Interface.Core;
using Eagles.Interface.DataAccess;

namespace Eagles.DomainService.Core
{
    public class UserHandler : IUserHandler
    {
        private readonly IPartyMemberDataAccess dataAccess;

        private readonly IOrganizationDataAccess OrgdataAccess;

        private readonly IBranchDataAccess BrcdataAccess;

        private readonly IMd5Helper md5Helper;

        private readonly ICacheHelper cacheHelper;

        private readonly IBranchDataAccess BrndataAccess;

        private readonly IOperDataAccess OperdataAccess;

        private readonly IAuditDataAccess auditdataAccess;


        public UserHandler(IAuditDataAccess auditdataAccess, IPartyMemberDataAccess dataAccess, IOrganizationDataAccess orgdataAccess, IConfigurationManager configurationManager, ICacheHelper cacheHelper, IMd5Helper md5Helper, IBranchDataAccess brcdataAccess, IBranchDataAccess brndataAccess, IOperDataAccess operdataAccess)
        {
            this.dataAccess = dataAccess;
            OrgdataAccess = orgdataAccess;
            this.cacheHelper = cacheHelper;
            this.md5Helper = md5Helper;
            BrcdataAccess = brcdataAccess;
            BrndataAccess = brndataAccess;
            OperdataAccess = operdataAccess;
            this.auditdataAccess = auditdataAccess;
        }

        public GetPartyMemberResponse GetPartyMemberList(GetPartyMemberRequest request)
        {

            var response = new GetPartyMemberResponse
            {
            };
            //  //得到试卷 + 习题的关系

            var token = cacheHelper.GetData<TbUserToken>(request.Token);

            var userinfo = OperdataAccess.GetOperDetail(token.UserId) ?? new TbOper();

            if (userinfo.BranchId > 0)
            {
                request.BranchId = userinfo.BranchId;
            }

            var list = dataAccess.GetUserInfoList(request, out int totalCount);

            if (list.Count == 0) throw new TransactionException("M01");

            var orgList = OrgdataAccess.GetOrganizationList(list.Select(x => x.OrgId).ToList());

            var branchList = BrndataAccess.GetBranchList(list.Select(x => x.BranchId).ToList());

            response.TotalCount = totalCount;
            response.List = list.Select(x => new Member
            {
                OrgId = x.OrgId,
                OrgName = orgList.FirstOrDefault(o => o.OrgId == x.OrgId)?.OrgName,
                Phone = x.Phone,
                UserId = x.UserId,
                UserName = x.Name,
                BranchId = x.BranchId,
                BranchName = branchList.FirstOrDefault(f => f.BranchId == x.BranchId)?.BranchName,
                MemberType = x.MemberType,
                Status = x.Status,
                CreateTime = x.CreateTime
                //OrgId=x.OrgId
            }).OrderByDescending(x => x.CreateTime).ToList();

            return response;

        }

        public GetUserInfoDetailResponse GetUserInfoDetail(GetUserInfoDetailRequest request)
        {

            var response = new GetUserInfoDetailResponse
            {

            };
            TbUserInfo detail = dataAccess.GetUserInfoDetail(request);

            if (detail == null) throw new TransactionException("M01");

            List<TbOrgInfo> orgList = OrgdataAccess.GetOrganizationList(new List<int> { detail.OrgId });

            List<TbBranch> brcList = BrcdataAccess.GetBranchList(new List<int> { detail.BranchId });

            response.Info = new UserInfoDetails
            {
                OrgName = orgList.FirstOrDefault(o => o.OrgId == detail.OrgId)?.OrgName,
                Phone = detail.Phone,
                UserId = detail.UserId,
                UserName = detail.Name,
                BeforJoinTime = detail.PreMemberTime,
                Birth = detail.Birthday,
                Company = detail.Company,
                DefaultAddress = detail.Address,
                Education = detail.Education,
                FamilyAddress = detail.OriginAddress,
                FormalJoinTime = detail.MemberTime,
                GraduateSchool = detail.School,
                IdCard = detail.IdNumber,
                // IsMoney=detail.
                // Nation = detail.Ethnic,
                NativePlace = detail.Origin,
                Picture = detail.NickPhotoUrl,
                Position = detail.Title,
                Sex = detail.Sex == "男" ? 0 : 1,
                BranchId = detail.BranchId,
                Status = detail.Status,
                Provice = detail.Provice,
                PhotoUrl = detail.PhotoUrl,
                UserStatus = detail.MemberType,
                City = detail.City,
                CreateTime = detail.CreateTime,
                Dept = detail.Dept,
                District = detail.Dept,
                //MemberStatus = detail.MemberStatus,
                Nation = detail.Ethnic,
                BranchName = brcList.FirstOrDefault(o => o.BranchId == detail.BranchId)?.BranchName,
                MemberType = detail.MemberType,
                OrgId = detail.OrgId,
                FeeExpireDate = detail.FeeExpireDate,
                Marital = detail.Marital == "已婚" ? 0 : 1
                


            };
            return response;
        }

        public bool RemoveUserInfoDetails(RemoveUserInfoDetailsRequest request)
        {

            return dataAccess.RemoveUserInfo(request) > 0;


        }

        public bool EditUserInfoDetails(EditUserInfoDetailsRequest request)
        {

            var tokenInfo = cacheHelper.GetData<TbUserToken>(request.Token);
            TbUserInfo mod;
            Regex regex = new Regex("^1[123456789]\\d{9}$");

            if (request.Info.Phone.Length != 11)
            {
                throw new TransactionException("M07");
            }



            var password = md5Helper.Md5Encypt(request.Info.Phone.Substring(request.Info.Phone.Length - 6));




            if (request.Info.UserId > 0)
            {

                var userInfo = dataAccess.GetUserInfoDetail(new GetUserInfoDetailRequest() { UserId = request.Info.UserId });


                if (userInfo.Phone != request.Info.Phone)
                {
                    if (dataAccess.CheckUserPhone(request.Info.Phone) > 0)
                    {
                        throw new TransactionException("M05");
                    }
                }

                mod = new TbUserInfo
                {
                    Phone = request.Info.Phone,
                    UserId = request.Info.UserId,
                    Name = request.Info.UserName,
                    PreMemberTime = request.Info.BeforJoinTime,
                    Birthday = request.Info.Birth,
                    Company = request.Info.Company,
                    Address = request.Info.DefaultAddress,
                    Education = request.Info.Education,
                    OriginAddress = request.Info.FamilyAddress,
                    MemberTime = request.Info.FormalJoinTime,
                    School = request.Info.GraduateSchool,
                    IdNumber = request.Info.IdCard,
                    // IsMoney   ,                                                                  
                    //Ethnic = request.Info.Nation,
                    Ethinc = request.Info.Nation,
                    Origin = request.Info.NativePlace,
                    OrgId = tokenInfo.OrgId,
                    NickPhotoUrl = request.Info.Picture,
                    Title = request.Info.Position,
                    Sex = request.Info.Sex == 0 ? "男" : "女",
                    IsCustomer = 1,
                    BranchId = request.Info.BranchId,
                    City = request.Info.City,
                    //  CreateTime = DateTime.Now,
                    Dept = request.Info.Dept,
                    District = request.Info.District,
                    EditTime = DateTime.Now,
                    // MemberStatus = request.Info.UserStatus,
                    MemberType = request.Info.MemberType,
                    OperId = tokenInfo.UserId,
                    //Password = password,
                    PhotoUrl = request.Info.PhotoUrl,
                    Provice = request.Info.Provice,
                    Ethnic = request.Info.Nation,
                    //IsLeader = 0,
                    //Score = 0,
                    Status=0,
                    FeeExpireDate = request.Info.FeeExpireDate,
                    Marital = request.Info.Marital == 0 ? "已婚" : "未婚"

                };

                return dataAccess.EditUserInfo(mod) > 0;


            }
            else
            {

                if (dataAccess.CheckUserPhone(request.Info.Phone) > 0)
                {
                    throw new TransactionException("M05");
                }


                mod = new TbUserInfo
                {

                    Ethinc = request.Info.Nation,
                    Phone = request.Info.Phone,
                    UserId = request.Info.UserId,
                    Name = request.Info.UserName,
                    PreMemberTime = request.Info.BeforJoinTime,
                    Birthday = request.Info.Birth,
                    Company = request.Info.Company,
                    Address = request.Info.DefaultAddress,
                    Education = request.Info.Education,
                    OriginAddress = request.Info.FamilyAddress,
                    MemberTime = request.Info.FormalJoinTime,
                    School = request.Info.GraduateSchool,
                    IdNumber = request.Info.IdCard,
                    // IsMoney   ,                                                                  
                    //Ethnic = request.Info.Nation,
                    Origin = request.Info.NativePlace,
                    OrgId = tokenInfo.OrgId,
                    NickPhotoUrl = request.Info.Picture,
                    Title = request.Info.Position,
                    Sex = request.Info.Sex == 0 ? "男" : "女",
                    IsCustomer = 1,
                    BranchId = request.Info.BranchId,
                    City = request.Info.City,
                    CreateTime = DateTime.Now,
                    Dept = request.Info.Dept,
                    District = request.Info.District,
                    EditTime = DateTime.Now,
                    MemberStatus = 0,
                    MemberType = request.Info.MemberType,
                    OperId = tokenInfo.UserId,
                    Password = password,
                    PhotoUrl = request.Info.PhotoUrl,
                    Provice = request.Info.Provice,
                    Status = 0,
                    Ethnic = request.Info.Nation,
                    IsLeader = 0,
                    Score = 0,
                    FeeExpireDate = request.Info.FeeExpireDate,
                    Marital = request.Info.Marital == 0 ? "已婚" : "未婚"

                };

                return dataAccess.CreateUserInfo(mod) > 0;
            }
        }

        public GetAuthorityUserSetUpResponse GetAuthorityUserSetUp(GetAuthorityUserSetUpRequset requset)
        {
            var response = new GetAuthorityUserSetUpResponse
            {

            };

            //获取用户下级权限
            List<TbUserRelationship> userSetUp = dataAccess.GetAuthorityUserSetUp(requset.UserId);

            if (userSetUp.Count == 0) throw new TransactionException("M01");

            response.TotalCount = 0;
            response.User = userSetUp.Select(x => new User
            {
                UserId = x.SubUserId,
                UserName = x.Name,
                Phone = x.Phone,
                BranchName = x.BranchName
            }).ToList();
            return response;
        }

        public bool CreateAuthorityUserSetUp(CreateAuthorityUserSetUp requset)
        {
            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            var list = requset.UserIds.Select(x => new TbUserRelationship
            {
                OrgId = token.OrgId,
                UserId = requset.UserId,
                SubUserId = x
            }).ToList();
            //删除以前的数据
            dataAccess.RemoveAuthorityUserSetUp(requset.UserId);

            return dataAccess.CreateAuthorityUserSetUp(list) > 0;
        }

        public bool RemoveAuthorityUserSetUp(RemoveAuthorityUserSetUp requset)
        {


            List<TbUserRelationship> list;


            list = requset.UserIds.Select(x => new TbUserRelationship
            {
                //  OrgId = requset.OrgId,
                UserId = requset.UserId,
                SubUserId = x
            }).ToList();

            return dataAccess.RemoveAuthorityUserSetUp(list) > 0;


        }

        public ImportUserResponse BatchImportUser(ImportUserRequest request)
        {

            var response = new ImportUserResponse { UserList = new List<ImportUser>() };
            Regex regex = new Regex("^1[123456789]\\d{9}$");
            var userinfo = new List<TbUserInfo>();
            var userinfo1 = new List<TbUserInfo>();

            var token = cacheHelper.GetData<TbUserToken>(request.Token);
            foreach (var md in request.UserList)
            {

                if (!(md.MemberType == 1 || md.MemberType == 0))
                {
                    md.ImportStatus = false;
                    md.ErrorReason = "党员类型错误！";
                    response.UserList.Add(md);
                    continue;
                }

                if (md.Phone.Length != 11)
                {
                    md.ImportStatus = false;
                    md.ErrorReason = "手机号格式错误！";
                    response.UserList.Add(md);
                    continue;
                }

                userinfo.Add(new TbUserInfo
                {
                    Name = md.UserName,
                    Phone = md.Phone,
                    MemberType = md.MemberType,
                    BranchId = request.BranchId,
                    OrgId = token.OrgId,
                    Password = md5Helper.Md5Encypt(md.Phone.Substring(md.Phone.Length - 6)),
                    Status = -1,
                    IsCustomer = 1,
                    Sex = md.Sex.ToString()
                });


            }

            if (userinfo.Count == 0)
            {
                throw new TransactionException("M12");
            }


            List<TbUserInfo> user = dataAccess.GetUserInfoListByPhone(userinfo.Select(x => x.Phone).ToList());

            userinfo.ForEach(x =>
            {
                if (user.Any(f => x.Phone == f.Phone))
                {
                    response.UserList.Add(new ImportUser()
                    {
                        ImportStatus = false,
                        ErrorReason = "手机号重复",
                        MemberType = x.MemberType,
                        Phone = x.Phone,
                        UserName = x.Name,
                        Sex = (Sex) Enum.Parse(typeof(Sex), x.Sex)
                    });
                }
                else
                {
                    userinfo1.Add(x);
                }
                //userinfo1.Add(user.Any(f => x.Phone == f.Phone) ? new TbUserInfo() : x);
            });

            if (userinfo1.Count == 0)
            {
                return response;
            }

            // userinfo1 = userinfo1.Where(x => x.OrgId > 0).ToList();

            if (dataAccess.CreateUserInfo(userinfo1) <= 0)
            {
                response.UserList.AddRange(userinfo1.Select(x => new ImportUser()
                {
                    ImportStatus = false,
                    ErrorReason = "添加数据库失败",
                    MemberType = x.MemberType,
                    Phone = x.Phone,
                    UserName = x.Name,
                    Sex = (Sex)Enum.Parse(typeof(Sex), x.Sex)
                }));
            }



            response.ImportStart = 1;

            if (response.UserList.Count > 0)
            {
                response.ImportStart = 2;
            }

            return response;

            // throw new NotImplementedException();
        }

        public bool CheckUserPhone(CheckUserPhoneRequest request)
        {

            return dataAccess.CheckUserPhone(request.Phone) > 0;

        }

        public GetUserLoginLsResponse GetUserLoginLs(GetUserLoginLsRequest request)
        {

            var response = new GetUserLoginLsResponse
            {
            };

            List<TbUserToken> list = OperdataAccess.GetUserLoginLs(request, out int totalCount);

            response.TotalCount = totalCount;
            response.List = list.Select(x => new UserLs
            {
                Phone = x.Phone,
                BranchName = x.BranchName,
                OrgName = x.OrgName,
                CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                Name = x.Name,
                IsCustomer = x.IsCustomer==1?"否":"是"
            }).ToList();

            return response;


        }

        public bool SendMsg(SendMsgRequest request)
        {

            if (!request.id.Any())
            {
                throw new TransactionException("M10");
            }

            var token = cacheHelper.GetData<TbUserToken>(request.Token);

            var list = new List<TbUserNotice>();

            foreach (var item in request.id)
            {

                var notice = new TbUserNotice()
                {
                    Content = request.Content,
                    UserId = item,
                    NewsType = int.Parse(request.NewsType),
                    FromUser = token.UserId,
                    OrgId = token.OrgId,
                    Title = request.Title,
                    IsRead = 1,
                    TargetUrl = request.TargetUrl,

                };

                list.Add(notice);
            }

            return auditdataAccess.SendUserNotice(list)>0;

            
        }
    }
}
